//
//  TTRecyclingUploadGoodsHeaderView.m
//  TaoTuo
//
//  Created by apple on 2020/9/17.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTRecyclingUploadGoodsHeaderView.h"
#import "TTDianpuUploadImageCollectionViewCell.h"
#import "LLImagePicker.h"
#import "YBImageBrowser.h"
#import "OSSRecyclingImageUploader.h"

static NSString *cellID = @"cell_id";
static NSString *addImageName = @"addimage";

@interface TTRecyclingUploadGoodsHeaderView ()<UICollectionViewDelegate, UICollectionViewDataSource, TTDianpuUploadImageCollectionViewCellDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, YYTextViewDelegate>
{
    TTDianpuUploadImageModel *lastModel;
}
@property (nonatomic, strong) YYTextView *textView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *imgUrlArray;  //上传的图片地址
/// 字数统计
@property (nonatomic, strong) UILabel *countLabel;

@end


@implementation TTRecyclingUploadGoodsHeaderView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = UIColor.cyanColor;
        self.refreshSubject = [RACSubject subject];
        [self textView];
        [self setupDatas];
        [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.bottom.equalTo(self.textView);
        }];
        
        @weakify(self)
        [RACObserve(self.textView, text) subscribeNext:^(NSString *  _Nullable text) {
            @strongify(self)
            self.countLabel.text = [NSString stringWithFormat:@"%ld/60", text.length];
        }];
        
    }
    return self;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuUploadImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    [cell setModel:self.dataArray[indexPath.row] canModify:YES];
    cell.delegate = self;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuUploadImageModel *model = self.dataArray[indexPath.row];
    if ([model.imageName isEqualToString:addImageName]) {
        [LLImagePicker imagePickerWithMaxImagesCount:(7 - self.dataArray.count) delegate:self baseViewController:self didFinishPickingPhotosHandle:^(NSArray<UIImage *> * _Nonnull photos, BOOL isSelectOriginalPhoto) {
            //上传图片到OSS, 添加model
            [[OSSRecyclingImageUploader sharedLoader] asyncUploadImages:photos complete:^(NSArray<NSString *> * _Nonnull names, UploadImageState state) {
                NSLog(@">>>> %@, state = %ld", names, state);
                for (NSString *urlStr in names) {
                    TTDianpuUploadImageModel *imgModel = [[TTDianpuUploadImageModel alloc] init];
                    imgModel.imageUrlString = urlStr;
                    [[self mutableArrayValueForKey:@"dataArray"] insertObject:imgModel atIndex:self.dataArray.count - 1];
                    [self.imgUrlArray insertObject:urlStr atIndex:self.imgUrlArray.count];
                }
                
                if (self.dataArray.count >= 7) {
                    [[self mutableArrayValueForKey:@"dataArray"] removeLastObject];
                }
                
                [self setupCollectionViewHeight];
                
                [self.collectionView reloadData];
            }];
        }];
        
    } else {
        // 查看图片
        @autoreleasepool {
            NSMutableArray *imgs = [NSMutableArray array];
            for (TTDianpuUploadImageModel *model in self.dataArray) {
                if (model.imageUrlString.length > 0) {
                    YBIBImageData *imageData = [YBIBImageData new];
                    imageData.imageURL = [NSURL URLWithString:model.imageUrlString];
                    [imgs addObject:imageData];
                }
            }
            YBImageBrowser *browser = [YBImageBrowser new];
            browser.dataSourceArray = imgs;
            browser.currentPage = indexPath.row;
            [browser show];
        }
        
    }
}


- (void)setupCollectionViewHeight
{
    CGFloat h = floor((SCREEN_WIDTH - 40) / 3.0);
    CGFloat rowCount = ceilf(self.dataArray.count / 3.0);
    self.collectionView.height = rowCount * h + 10;
    self.height = self.collectionView.bottom + 10;
    
    [self.refreshSubject sendNext:@1];
    
}

// 拍照或选取图片完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    // 图片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //上传图片到OSS, 添加model
    [[OSSRecyclingImageUploader sharedLoader] asyncUploadImage:image complete:^(NSArray<NSString *> * _Nonnull names, UploadImageState state) {
        NSLog(@">>>> %@, state = %ld", names, state);
        NSString *urlStr = names.firstObject;
        TTDianpuUploadImageModel *imgModel = [[TTDianpuUploadImageModel alloc] init];
        imgModel.imageUrlString = urlStr;
        [[self mutableArrayValueForKey:@"dataArray"] insertObject:imgModel atIndex:0];
        [self.imgUrlArray insertObject:urlStr atIndex:0];
        [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]];
        if (self.dataArray.count >= 7) {
            [[self mutableArrayValueForKey:@"dataArray"] removeLastObject];
            [self.collectionView reloadData];
        }
        
        [self setupCollectionViewHeight];
        
    }];
    
}

#pragma mark - TTDianpuUploadImageCollectionViewCellDelegate
// 删除图片
- (void)imageCell:(TTDianpuUploadImageCollectionViewCell *)imageCell deleteModel:(TTDianpuUploadImageModel *)model
{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:imageCell];
    [[self mutableArrayValueForKey:@"dataArray"] removeObject:model];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    
    if (self.dataArray.lastObject != lastModel) {
        [[self mutableArrayValueForKey:@"dataArray"] addObject:lastModel];
    }
    [self.collectionView reloadData];
    [self setupCollectionViewHeight];
    
    for (NSString *urlStr in self.imgUrlArray) {
        if ([urlStr isEqualToString:model.imageUrlString]) {
            [self.imgUrlArray removeObject:urlStr];
            break;
        }
    }
}


- (void)setupDatas
{
    [[self mutableArrayValueForKey:@"dataArray"] removeAllObjects];
    // 添加一个添加图片的按钮
    lastModel = [[TTDianpuUploadImageModel alloc] init];
    lastModel.imageName = addImageName;
    [[self mutableArrayValueForKey:@"dataArray"] addObject:lastModel];
    
    [self.collectionView reloadData];
    
    [self setupCollectionViewHeight];
    
}





- (BOOL)textView:(YYTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (text.length == 0) {
        return YES;
    }
    return textView.text.length < 60;
}


- (YYTextView *)textView
{
    if (!_textView) {
        _textView = [[YYTextView alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH - 20, 60)];
        _textView.placeholderText = @"";
        _textView.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
        _textView.textColor = UIColorHex(333333);
        _textView.placeholderTextColor = UIColorHex(999999);
        _textView.delegate = self;
        [self addSubview:_textView];
    }
    return _textView;
}

- (UILabel *)countLabel
{
    if (!_countLabel) {
        _countLabel = [UILabel labelWithTitle:@"0/60" color:UIColorHex(999999) fontSize:12];
        [self addSubview:_countLabel];
    }
    return _countLabel;
}


- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        CGFloat w = floor((SCREEN_WIDTH - 40) / 3.0);
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(w, w);
        layout.minimumLineSpacing = 5;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
        CGFloat h = w + 5;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, self.textView.bottom + 5, self.textView.width, h) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[TTDianpuUploadImageCollectionViewCell class] forCellWithReuseIdentifier:cellID];
        [self addSubview:_collectionView];
    }
    return _collectionView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}



@end
